package com.hb.gateway.util;

import cn.hutool.json.JSONUtil;
import org.fzzn.core.model.msg.Message;
import org.fzzn.core.model.msg.ResponseDto;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/***
 * 返回结果工具类
 */
public class ResponseUtil {

    /***
     * ServerWebExchange 返回结果
     * @param exchange
     * @param result
     * @return
     */
    public static Mono<Void> buildResponse(ServerWebExchange exchange, ResponseDto result) {
        ServerHttpResponse response = exchange.getResponse();
        return buildResponse(response, result);
    }

    /***
     * ServerHttpResponse 返回结果信息
     * @param response
     * @param result
     * @return
     */
    public static Mono<Void> buildResponse(ServerHttpResponse response, ResponseDto result) {
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        response.setStatusCode(HttpStatus.OK);

        return response.writeWith(Mono.fromSupplier(() -> {
            DataBufferFactory bufferFactory = response.bufferFactory();
            return bufferFactory.wrap(JSONUtil.toJsonStr(result).getBytes());
        }));
    }

}
